import CryptoJS from 'crypto-js'
const { AES } = CryptoJS
const password = 'baike tenmillionbaike tenmillion'
const iv = 'baike tenmillion'
const accInfo = wx.getAccountInfoSync()
const env = accInfo.miniProgram.envVersion
const isDev = env === 'develop'

/**
 * @param {string} data
 */
const enCode = (data) => {
  var ciphertext = AES.encrypt(data, password, {
    iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  }).toString()
  return ciphertext
}
// 解密
const deCode = (data) => {
  const bytes = AES.decrypt(data, password, {
    iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  const originalText = bytes.toString(CryptoJS.enc.Utf8)
  return originalText
}

/**
 * @description 对象或数组中为null的属性值转换为字符串
 */
function nul2str(objOrList) {
  if (objOrList === null || objOrList === undefined) {
    return ''
  }
  const res0 = JSON.parse(JSON.stringify(objOrList))
  if (Array.isArray(res0)) {
    res0.forEach((item, index) => {
      res0[index] = nul2str(item)
    })
  } else if (typeof res0 === 'object') {
    Object.keys(res0).forEach((key) => {
      res0[key] = nul2str(res0[key])
    })
  }
  return res0
}

const FormatResponse = (response) => {
  let tmp = response
  if (isDev) {
    return nul2str(response)
  }
  const resObj = JSON.parse(deCode(response.data))
  const res1 = nul2str(resObj)
  const res = {
    ...tmp,
    data: res1
  }
  return res
}
// 敏感信息加密隐藏一下
const cryptoStore = {
  getStorageSync: (key) => {
    const res = wx.getStorageSync(key) || {}
    if (typeof res === 'object') {
      return res
    } else {
      return JSON.parse(deCode(res))
    }
  },
  getStorage: ({ key, success, fail, complete }) => {
    return wx.getStorage({
      key,
      fail,
      complete,
      success: ({ errMsg, data }) => {
        data = JSON.parse(deCode(data))
        success({ errMsg, data })
      }
    })
  },
  setStorageSync: (key, data) => {
    if (env == 'develop') {
      // 仅仅开发环境存放一下
      wx.setStorageSync(`${key}_dev_visible`, data)
    }
    return wx.setStorageSync(key, enCode(JSON.stringify(data)))
  },
  setStorage: ({ key, data, success, fail, complete }) => {
    return wx.setStorage({
      key,
      fail,
      complete,
      success: (res) => {
        success(res)
        if (env == 'develop') {
          wx.setStorageSync(`${key}_dev_visible`, data)
        }
      },
      data: enCode(JSON.stringify(data))
    })
  }
}

export {
  FormatResponse,
  cryptoStore,

}